package com.application.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;

public abstract class RetrivierWeb {
	protected Logger		logger;
	protected List<String>	desendencia;
	public RetrivierWeb() {
		logger = Logger.getLogger(getClass());
		desendencia = new LinkedList<String>();
	}

	public abstract void processContent(String data, String parentName);
        public abstract void retrieve();
	public String getWebPageContent(String url, String beginPatter, String endPatter, String charset) {
		String value = "";
		BufferedReader in = null;
		boolean begin = false;
		// boolean end=false;
		try {
			if(charset==null || charset.isEmpty()){
				charset = "utf-8";
			}
			URL webPage = new URL(url);
			URLConnection yc = webPage.openConnection();
//			in = new BufferedReader(new InputStreamReader(yc.getInputStream(),"utf-8"));
//			in = new BufferedReader(new InputStreamReader(yc.getInputStream(),"iso-8859-1"));
			in = new BufferedReader(new InputStreamReader(yc.getInputStream(),charset));
//			in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
			String inputLine;
			while ((inputLine = in.readLine()) != null) {
				logger.info(inputLine);
				if (begin && endPatter != null && inputLine.contains(endPatter)) {
					break;
				}
				if (beginPatter == null || inputLine.contains(beginPatter)) {
					begin = true;
				}
				if (begin) {
					value += inputLine;
				}
			}

		} catch (Exception e) {
			logger.error(e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return value;
	}

	public void retrivie(String url,String parentName,String beginPatter, String endPatter,String charset) {
		String paginaWeb = "";
		try {
			paginaWeb = getWebPageContent(url, beginPatter, endPatter,charset);
			if (!paginaWeb.isEmpty()) {
                                if(parentName!=null){
                                    desendencia.add(parentName);
                                }                                
				processContent(paginaWeb,parentName);
			}
		} catch (Exception e) {
			logger.error(e);
		} finally {
		}
	}

	protected String getElementForContent(String data, String regex, Integer groupNumber) {
		String value = "";
		Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
		Matcher matcher = pattern.matcher(data);
		if (matcher.find()) {
			value = matcher.group(groupNumber);
		}
		return value;
	}
	protected String escapeSql(String data){
		return StringEscapeUtils.escapeSql(data);
	}
	protected String unescapeHtml(String data){
		return StringEscapeUtils.unescapeHtml(data);
	}
	protected String escapeValue(String dato){
		String value = "";
//		value = StringEscapeUtils.unescapeXml(dato);
		value = dato;
		return value;
	}
	protected String getWhereColegioUpdate(String pais,String provincia,String partido,String nameColegio, String zonaKey){
		String where ="";
		if(zonaKey.equals("Capital Federal")){
			
			where = " name='"+escapeSql(nameColegio)+"' AND " +
			" pais_id= (SELECT id FROM pais where UPPER(name)=UPPER('"+pais+"')) AND " +
			" provincia_id= (SELECT provincia_id FROM partido where UPPER(name)=UPPER('"+zonaKey+"')) AND " +
			" partido_id= (SELECT id FROM partido where UPPER(name)=UPPER('"+zonaKey+"')) AND" +
			" localidad_id = (SELECT id FROM localidad where "+getWherePartidoName(partido)+" AND " +
				" partido_id = (SELECT id FROM partido where UPPER(name)=UPPER('"+zonaKey+"')) )"+
					"";
		}else{
		where = " name='"+escapeSql(nameColegio)+"' AND " +
				" pais_id= (SELECT id FROM pais where UPPER(name)=UPPER('"+pais+"')) AND " +
				" provincia_id= (SELECT provincia_id FROM partido where UPPER(name)=UPPER('"+partido+"')) AND " +
				" partido_id= (SELECT id FROM partido where UPPER(name)=UPPER('"+partido+"'))";
		}
		return where;
	}
	protected String getWherePartidoName(String partidoName){
		String result = "";
		//(UPPER(name) LIKE UPPER('%Villa%') OR UPPER(name) LIKE UPPER('%Urquiza%'))
		String[] datos = partidoName.split(" ");
		int size = datos.length;
		List<String> list = new LinkedList<String>();
		for (int i = 0; i < size; i++) {
			String item = datos[i].trim();
			if(item.length()>3){
				list.add(" UPPER(name) LIKE UPPER('%"+item+"%') ");				
			}
		}
		result = list.toString();
		result = result.replace(",", " OR ");
		result = result.replace("[", " ( ");
		result = result.replace("]", " ) ");
		return result;
	}
}
